<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="档案室名称" prop="archiveId">
        <el-select v-model="queryParams.archiveId" allow-create clearable
                   default-first-option
                   filterable placeholder="请输入档案室名称" size="small">
          <el-option v-for="(item, index) in archiveOptions" :key="index" :disabled="item.disabled"
                     :label="item.archiveName" :value="item.archiveId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="档案柜名称" prop="filingName">
        <el-input
          v-model="queryParams.filingName"
          placeholder="请输入档案柜名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <div class="cabinet-container">
      <div v-for="(row, rowIndex) in cabinetMatrix" :key="rowIndex" class="cabinet-row">
        <div
          v-for="(col, colIndex) in row"
          :key="colIndex"
          class="cabinet-cell"
          @mouseenter="hoverCell(rowIndex, colIndex, col)"
          @mouseleave="resetCell(rowIndex, colIndex, col)"
          @click="chufa(col.filingId)"
        >
          <div class="archive-name">{{ col.filingName }}</div>
          <div class="archive-description">{{ col.filingDescription }}</div>
          <div class="archive-creater">{{ col.creater }}</div>
          <div class="archive-createDate">{{ col.createDate }}</div>
        </div>
      </div>
    </div>


    <!-- 添加或修改档案柜管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="档案室名称" prop="archiveId">
          <el-select v-model="form.archiveId" allow-create clearable
                     default-first-option
                     :disabled="noWrite"
                     filterable placeholder="请输入档案室名称" size="small" :style="{width: '100%'}">
            <el-option v-for="(item, index) in archiveOptions" :key="index" :disabled="item.disabled"
                       :label="item.archiveName" :value="item.archiveId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="档案柜名称" prop="filingName">
          <el-input v-model="form.filingName" placeholder="请输入档案柜名称"/>
        </el-form-item>
        <el-form-item label="档案柜描述" prop="filingDescription">
          <el-input v-model="form.filingDescription" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title1" :visible.sync="open1" width="500px" append-to-body>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="handleSearch">查 询</el-button>
        <el-button type="primary" @click="handleUpdate">修 改</el-button>
        <el-button type="primary" @click="handleDelete">删 除</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title2" :visible.sync="open2" width="1000px" append-to-body>
      <el-form :model="queryParams1" ref="queryForm1" :inline="true" v-show="showSearch1" label-width="88px">
        <el-form-item label="档案名称" prop="fileDetailName">
          <el-input
            v-model="queryParams1.fileDetailName"
            placeholder="请输入档案名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery1"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery1">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery1">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd1"
          >新增
          </el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="fileDetailList">
        <el-table-column label="档案名称" align="center" prop="fileDetailName"/>
        <el-table-column label="档案柜描述" align="center" prop="fileDetailDescription"/>
        <el-table-column label="上传时间" align="center" prop="createDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate1(scope.row)"
            >修改
            </el-button>
            <a :href="scope.row.fileDetailUrl" target="_blank" rel="noopener noreferrer" download>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-download"
              >下载
              </el-button>
            </a>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete1(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :limit.sync="queryParams1.pageSize"
        :page.sync="queryParams1.pageNum"
        :total="total"
        @pagination="fetchCabinetData1"
      />
    </el-dialog>


    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-input v-model="upload.fileDetailName" placeholder="请输入档案名称"/>
      <el-input v-model="upload.fileDetailDescription" type="textarea" placeholder="请输入内容"/>
      <el-input v-model="upload.filingId" type="hidden"/>
      <el-upload
        ref="upload"
        :action="upload.url + '?fileDetailName='+upload.fileDetailName + '&fileDetailDescription='+upload.fileDetailDescription + '&filingId='+upload.filingId "
        :auto-upload="false"
        :disabled="upload.isUploading"
        :headers="upload.headers"
        :limit="1"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        accept=".*"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancelFileForm">取 消</el-button>

      </div>
    </el-dialog>


    <el-dialog :title="title3" :visible.sync="open3" width="500px" append-to-body>
      <el-form ref="form3" :model="form3" :rules="rules3" label-width="100px">
        <el-form-item label="档案名称" prop="fileDetailName">
          <el-input v-model="form3.fileDetailName" placeholder="请输入档案名称"/>
        </el-form-item>
        <el-form-item label="档案描述" prop="fileDetailDescription">
          <el-input v-model="form3.fileDetailDescription" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {listCabinet} from "@/api/fund/archiveCabinet";
import {
  addFilingCabinet,
  delFilingCabinet,
  getFilingCabinet,
  listFilingCabinet,
  updateFilingCabinet
} from "@/api/fund/filingCabinet";
import {delFileDetail, getFileDetail, listFileDetail, updateFileDetail} from "@/api/fund/fileDetail";
import {getToken} from "@/utils/auth";


export default {
  name: "filingCabinet",
  data() {
    return {

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/fund/fileDetail/upload"
      },
      total: 0,
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      noWrite: false,
      // 显示搜索条件
      showSearch: true,
      showSearch1: true,
      archiveId: null,
      filingId: null,
      // 档案管理表格数据
      cabinetMatrix: [],
      fileDetailList: [],
      archiveOptions: [{}],
      // 弹出层标题
      title: "",
      title1: "",
      title2: "",
      title3: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      open2: false,
      open3: false,
      // 查询参数
      queryParams: {},
      queryParams1: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      form1: {},
      form3: {},
      rules: {
        archiveId: [
          {required: true, message: "档案室不能为空", trigger: "blur"}
        ],
        filingName: [
          {required: true, message: "档案柜名称不能为空", trigger: "blur"}
        ],
      },
      rules3: {
        fileDetailName: [
          {required: true, message: "档案名称不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.listCabinet();
    this.fetchCabinetData();
  },
  methods: {
    /** 档案柜触发操作 */
    chufa(date) {
      this.open1 = true;
      this.filingId = date;
      this.resetForm("queryForm1");
    },

    /** 查询档案室管理列表 */
    listCabinet() {
      listCabinet().then(response => {
        this.archiveOptions = response.rows;

      });
    },

    /** 搜索档案柜操作 */
    handleQuery() {
      this.fetchCabinetData();
    },

    /** 重置档案柜操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.resetQueryData();
    },

    /** 搜索档案操作 */
    handleQuery1() {
      this.fetchCabinetData1();
    },

    /** 重置档案操作 */
    resetQuery1() {
      this.resetForm("queryForm1");
      this.handleQuery1();
    },

    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
      this.form1 = {};
      this.resetForm("form1");
      this.form3 = {};
      this.resetForm("form3");
    },

    /** 新增档案柜操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.noWrite = false;
      this.title = "添加档案柜管理";
    },

    /** 上传档案操作 */
    handleAdd1() {
      this.upload.title = "用户导入";
      this.upload.open = true;
      this.upload.filingId = this.filingId;
    },

    /** 档案明细列表 */
    handleSearch() {
      this.open2 = true;
      this.open1 = false;
      this.fetchCabinetData1();
    },

    fetchCabinetData() {
      if (this.queryParams.archiveId == null) {
        this.$modal.msgError("必须选择档案室！");
      } else {
        listFilingCabinet(this.queryParams).then(response => {
          this.cabinetMatrix = this.transformToMatrix(response.rows);
        });
      }

    },

    resetQueryData() {
      listFilingCabinet(this.queryParams).then(response => {
        this.cabinetMatrix = this.transformToMatrix(response.rows);
      });

    },

    fetchCabinetData1() {
      this.loading = true;
      this.queryParams1.filingId = this.filingId
      listFileDetail(this.queryParams1).then(response => {
        this.fileDetailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    transformToMatrix(data) {
      // 将数据转换为矩阵形式
      let matrix = [];
      // 假设每行有5列
      let cols = 8;
      for (let i = 0; i < data.length; i += cols) {
        matrix.push(data.slice(i, i + cols));
      }
      return matrix;
    },

    /** 修改档案柜操作 */
    handleUpdate(row) {
      const filingId = this.filingId
      getFilingCabinet(filingId).then(response => {
        this.form = response.data;
        this.open = true;
        this.noWrite = true;
        this.title = "修改档案柜管理";
      });
    },

    /** 档案柜提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.filingId != null) {
            updateFilingCabinet(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.open1 = false;
              this.fetchCabinetData();
              this.reset();
            });
          } else {
            addFilingCabinet(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.fetchCabinetData();
              this.reset();
            });
          }
        }
      });
    },

    /** 档案修改按钮 */
    submitForm1() {
      this.$refs["form3"].validate(valid => {
        updateFileDetail(this.form3).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open3 = false;
          this.fetchCabinetData1();
          this.reset();
        });
      });
    },

    // 档案柜取消按钮
    cancel() {
      this.open = false;
      this.fetchCabinetData();
      this.reset();
    },

    // 档案取消按钮
    cancel1() {
      this.open3 = false;
      this.fetchCabinetData1();
      this.reset();
    },

    /** 档案室删除按钮操作 */
    handleDelete(row) {
      const filingId = this.filingId;
      this.$modal.confirm('是否确认删除档案柜管理编号为"' + filingId + '"的数据项？').then(function () {
        return delFilingCabinet(filingId);
      }).then(() => {
        this.fetchCabinetData();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    handleUpdate1(row) {
      this.reset();
      const fileDetailId = row.fileDetailId;
      getFileDetail(fileDetailId).then(response => {
        this.form3 = response.data;
        this.open3 = true;
        this.title3 = "修改档案信息";
      });
    },

    /** 档案删除按钮操作 */
    handleDelete1(row) {
      const fileDetailId = row.fileDetailId;
      this.$modal.confirm('是否确认删除档案管理编号为"' + fileDetailId + '"的数据项？').then(function () {
        return delFileDetail(fileDetailId);
      }).then(() => {
        this.fetchCabinetData1();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    hoverCell(rowIndex, colIndex,col) {
      if(col.filingDescription.length>5){
        col.filingDescription = col.filingDescription1;
      }
      // 动态改变悬停格子的样式
      const cell = this.$el.querySelector(`.cabinet-row1:nth-child(${rowIndex + 1}) .cabinet-cell1:nth-child(${colIndex + 1})`);
      if (cell) {
        cell.style.backgroundColor = '#e0f7fa'; // 悬停时的背景色
      }
    },
    resetCell(rowIndex, colIndex,col) {
      if(col.filingDescription.length>5){
        col.filingDescription = col.filingDescription.slice(0, 5)+"...";
      }
      // 恢复格子的样式
      const cell = this.$el.querySelector(`.cabinet-row1:nth-child(${rowIndex + 1}) .cabinet-cell1:nth-child(${colIndex + 1})`);
      if (cell) {
        cell.style.backgroundColor = ''; // 恢复默认背景色
      }
    },
    cancelFileForm() {
      this.upload.open = false;
      this.upload.fileDetailName = null;
      this.upload.fileDetailDescription = null;
      this.upload.filingId = null;
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.fetchCabinetData1();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
      this.upload.fileDetailName = null;
      this.upload.fileDetailDescription = null;
      this.upload.filingId = null;
    },

  }
};
</script>
<style scoped>

.archive-name {
  font-size: 18px;
  font-weight: bold;
  color: #0b0b0b;
  margin-bottom: 8px;
}

.archive-description {
  font-size: 14px;
  color: #ea6f06;
}

.archive-creater {
  font-size: 14px;
  color: #0b77fd;
}

.archive-createDate {
  font-size: 14px;
  color: #0b77fd;
}


.cabinet-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.cabinet-row {
  display: flex;
  gap: 15px;
}

.cabinet-cell {
  padding: 20px;
  background: linear-gradient(135deg, #ffffff, #f9f9f9);
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
  text-align: center;
  width: 180px;
  height: 120px;
  background: #fff url("~@/assets/logo/档案柜.jpg");
  background-repeat: no-repeat;
  background-position: left bottom;
  text-align: right;
}

.cabinet-cell:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
  background: linear-gradient(135deg, #f0f7f8, #e8f4ff);
}
.cabinet-cell:hover .archive-name,
.cabinet-cell:hover .archive-creater,
.cabinet-cell:hover .archive-createDate{
  display: none;
}
.cabinet-cell:hover .archive-description{
  text-align: center;
}

</style>
